package cn.wangqi.personal.redis;

import org.apache.log4j.Logger;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by admin on 2017/10/13.
 */
public class RedisSessionDao extends AbstractSessionDAO {

    private static Logger logger = Logger.getLogger(RedisSessionDao.class);

    /**
     * The Redis key prefix for the sessions
     */
    private String keyPrefix = "shiro_redis_session:";

    /**
     * shiro-redis的session对象前缀
     */
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);
        logger.debug("创建seesion,id="+session.getId().toString());
        redisTemplate.setex(getKey(session.getId().toString()), 1800,(Serializable)session);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        logger.debug("获取seesion,id="+sessionId.toString());
        Session readSession = null;
        try {
            readSession=(Session) redisTemplate.get(getKey(sessionId.toString()));
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return readSession;
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        logger.debug("更新seesion,id="+session.getId().toString());
        if(session == null || session.getId() == null){
            logger.error("session or session id is null");
            return;
        }
        redisTemplate.setex(getKey(session.getId().toString()), 1800,(Serializable)session);
    }

    @Override
    public void delete(Session session) {
        logger.debug("删除seesion,id="+ session.getId().toString());
        String key=getKey(session.getId().toString());
        redisTemplate.delKey(key);
    }

    @Override
    public Collection<Session> getActiveSessions() {
        Set<Session> sessions = new HashSet<Session>();
        logger.info("获取存活的session");
        List<String> keys = redisTemplate.hkeys(this.keyPrefix + "*");
        if(keys != null && keys.size()>0){
            for(String key:keys){
                Session s = (Session) redisTemplate.get(key);
                sessions.add(s);
            }
        }
        return sessions;
    }

    private String getKey(String originalKey) {
        return keyPrefix+originalKey;
    }
}
